//
//  YSUserViewModel.swift
//  新浪浪
//
//  Created by mac on 16/2/29.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import AFNetworking

class YSUserViewModel: NSObject {

    //设置单例
    static let shareInstance = YSUserViewModel()
    //给这个model赋值
    var model: YSUserModel?
    
    //access_token 使用 实现它的get方法 也就是计算型属性
    
    
    var access_token:String? {
        return model?.access_token
    }
    
    
    
    var isLogin: Bool? {
         model = YSUserModel.readObject("info.aaaaa")
        return model?.access_token != nil ?  true : false
        
    }
 
    
    
    func loadToken(code:String,success: ()->(),faild: ()->()){
        /*  let params = ["client_id": App_KEY,
        "client_secret":APP_SECERT,
        "grant_type":"authorization_code",
        "code":code,
        "redirect_uri":App_URL
        ]    */
        let params = [
            "client_id":App_KEY,
            "client_secret":APP_SECERT,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":App_URL
        ]
        
        let afn = AFHTTPSessionManager()
        
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
        //https://api.weibo.com/oauth2/access_token
        afn.POST("https://api.weibo.com/oauth2/access_token", parameters: params, progress: nil, success: { (_ , JSON) -> Void in
            print("成功")
            
            
            if let dic = JSON as? [String : NSObject]{
                let model = YSUserModel (dic: dic)
                let token = model.access_token
                print(token)
                
//                success()
//                self.model = model
//                self.getUserInfo(model)
                self.getUserInfo(model, success: success, faild: faild)
                
                
            }
            
            }) { (_ , error) -> Void in
                print("失败")
        }
    }
    
    func getUserInfo(model:YSUserModel,success:()->(),faild:()->()){
        let manager = AFHTTPSessionManager()
        let parameters = ["access_token":model.access_token ?? "",
            "uid":model.uid ?? ""]
        manager.GET("https://api.weibo.com/2/users/show.json", parameters: parameters, progress: nil, success: { (_, JSON ) -> Void in
            print(JSON)
            
            if let dic = JSON as? [String:NSObject]{
                
                //处理json
                model.profile_image_url = dic["profile_image_url"]as? String
                model.screen_name = dic["screen_name"]as? String
                model.save("info.aaaaa")
                print("存储成功")
                success()
            }
            
            }) { (_ , error) -> Void in
                print(error)
                faild()
        }
        
    }
    
    
}




